package com.lantosec.hmrp.modules.warning.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.tree.TreeNodeVo;
import com.lantosec.hmrp.modules.warning.entity.WarningType;
import com.lantosec.hmrp.modules.warning.mapper.WarningTypeMapper;
import com.lantosec.hmrp.modules.warning.service.IWarningTypeService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-05-19
 */
@Service
@Primary
@Log4j2
public class WarningTypeServiceImpl extends ServiceImpl<WarningTypeMapper, WarningType> implements IWarningTypeService {
    @Override
    public List<TreeNodeVo> getWarningTypeTree() {
        return warningTypeTree(null);
    }

    private List<TreeNodeVo> warningTypeTree(String typeId) {
        List<TreeNodeVo> list = areaList(typeId);
        List tree = new ArrayList<TreeNodeVo>();
        if (list != null && list.size() > 0) {
            list.forEach(node -> {
                if (!node.isLeaf()) {
                    List<TreeNodeVo> children = warningTypeTree(node.getKey());
                    node.setChildren(children);
                }
                tree.add(node);
            });
        }
        return tree;
    }

    private List<TreeNodeVo> areaList(String typeId) {
        List<WarningType> list = getTypeById(typeId);
        if (list != null && list.size() > 0) {
            List<TreeNodeVo> nodes = new ArrayList<TreeNodeVo>();
            list.forEach( result -> {
                nodes.add(new TreeNodeVo( result.getTypeId(),result.getTypeName()));
            });
            return nodes;
        }
        return new ArrayList<TreeNodeVo>();
    }

    private List<WarningType> getTypeById(String typeId) {
        return baseMapper.getTypeById(typeId);
    }

    @Override
    public void create(WarningType entity) {
        String parentId = entity.getParentId();
        String typeId = null;
        if(StringUtils.isNotEmpty(parentId)){
            typeId = baseMapper.queryMaxTypeIdByParentId(parentId);
            entity.setTypeId(StringUtils.isEmpty(typeId)? parentId + "001" : typeId);
        }else{
            typeId = baseMapper.queryMaxTypeId();
            entity.setTypeId(StringUtils.isEmpty(typeId)? "001" : typeId);
        }
        baseMapper.insert(entity);
    }
}
